<template>
    <div class="ma-content-block flex flex_column p-4" style='height:85vh'>
        <div class="flex justify-between home-page-title " style="margin-bottom:2%">
            <div class='flex' >
                <div class='flex ' style='align-items:center;margin-right:24px'>
                    <div style='width:80px'>付款公司：</div>
                    <a-select :style="{width:'250px'}" :options="qsgsArr" v-model="qsgs" placeholder="请选择付款公司" allow-clear @change="handleChangeqsgs"></a-select>
                </div>
                <a-popover title="结算导出" position="bottom">
                    <a-button type="primary" >选择月份</a-button>
                    <template #content>
                        <a-month-picker style="width: 300px;" :hide-trigger="true" show-time @ok="handleExport($event)" />
                    </template>
                </a-popover>
                <div class="datetime  flex" style="margin-left:24px">
                    <a-range-picker
                        mode="month"
                        style="width: 268px"
                        v-model="currentTime"
                        @change="onChange"
                    >
                        <span
                        >
                        自定义
                        </span>
                    </a-range-picker>
                </div>
            </div>
            <a-button type="primary" @click='handleExports'>导 出</a-button>
        </div>
        <div class='tableBox flex flex_column flex_1' style='max-height:80%;'>
            <!-- 表头 -->
            <div class='flexbox height40 bor_btm' style='background:rgba(242, 243, 245,1)'>
                <div style='font-size:20px;font-weight:600'>{{column[0].title}}</div>
            </div>
            <div class="flex" style='background:rgba(242, 243, 245,1);font-weight:600'>
                <div class="calc1 flexbox bor_right bor_btm">
                    <div>客户名称</div>
                </div>
                <div class="calc1 flexbox bor_right bor_btm">
                    <div>合同号</div>
                </div>
                <div class="calc2 bor_right bor_btm">
                    <div class="flexbox height40 bor_btm">
                        <div >业务项目</div>
                    </div>
                    <div class="flexbox">
                        <div class="flexbox height40 flex_1 bor_right">
                            <div >品名分类</div>
                        </div>
                        <div class="flexbox height40 flex_1">
                            <div >计费服务类型</div>
                        </div>
                    </div>
                </div>
                <div class="calc1 flexbox bor_right bor_btm">
                    <div>总价（元）</div>
                </div>
                <div class="calc1 flexbox bor_right bor_btm">
                    <div>结算比例</div>
                </div>
                <div class="calc1 flexbox bor_right bor_btm">
                    <div>{{qsgs=='威斯腾'?'天一集团威斯腾物流':'天一集团威斯腾物流'}}</div>
                </div>
                <div class="calc1 flexbox bor_btm">
                    <div>备注</div>
                </div>
            </div>
            <div class='flex_1 scrollbar' style='overflow:auto'>
                <!-- 主体 -->
                <div class="flex" v-for="(item,index) in displayData" v-key='index'>
                    <!-- 客户名 -->
                    <div class="calc1 flexbox bor_right bor_btm">
                        <div class='pad8 height40'>{{item.name}}</div>
                    </div>
                    <div class="calc7   " >
                        <div style='width:100%' class='flex' v-for="(ite,inde) in item.contrat_list" v-key='inde'>
                        <!-- 合同名 -->
                            <div class=" bor_right height40 flexbox bor_btm" style='width:calc(100% / 7)'>
                                <div class="pad8 ">{{ite.contract_no}}</div>
                            </div>
                            <div class="flex_1 ">
                                <div class='flex height40' v-for="(it,ind) in ite.goods_type_list"  v-key='ind'>
                                    <!-- 品名名 -->
                                    <div class='flexbox bor_btm  bor_right' style='width:calc(100% / 6)'>
                                        <div class='pad8'>{{it.name}}</div>
                                    </div>
                                    <div class='flex flex_column flex_1'>
                                        <div class='flex' style='width:100%' v-for="(items,indexs) in it.price_list" v-key='indexs'>
                                            <!-- 服务名 -->
                                            <div class ="flex_1 flex height40">
                                                <div class="flexbox bor_btm  bor_right" style='width:100%'>
                                                    <div class='pad8'>{{items.pay_name}}</div>
                                                </div>
                                            </div>
                                            <!-- 总价 -->
                                            <div class ="flex_1 flex height40">
                                                <div class="flexbox bor_btm  bor_right" style='width:100%'>
                                                    <div class='pad8'>{{items.pay_price}}</div>
                                                </div>
                                            </div>
                                            <!-- 比例 -->
                                            <div class ="flex_1 flex height40">
                                                <div class="flexbox bor_btm  bor_right" style='width:100%'>
                                                    <div class='pad8'>{{items.bili}}</div>
                                                </div>
                                            </div>
                                            <!-- 结算金额 -->
                                            <div class ="flex_1 flex height40">
                                                <div class="flexbox bor_btm  bor_right" style='width:100%'>
                                                    <div class='pad8'>{{items.jiesuan}}</div>
                                                </div>
                                            </div>
                                            <!-- 备注 -->
                                            <div class ="flex_1 flex height40">
                                                <div class="flexbox bor_btm  " style='width:100%'>
                                                    <div class='pad8'>{{items.remark}}</div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <!-- 总计 -->
                <div class='flex'>
                    <div class="calc3 flexbox bor_right bor_btm">
                        <div class='pad8 height40'>总计</div>
                    </div>
                    <div class=' flex_1 '>
                        <div style='width:100%' class='flex' v-for='(item,index) in displayzongData' :key="index">
                            <div class ="flex_1 flex height40">
                                <div class="flexbox bor_btm  bor_right" style='width:100%'>
                                    <div class='pad8'>{{item.pay_name}}</div>
                                </div>
                            </div>
                            <div class ="flex_1 flex height40">
                                <div class="flexbox bor_btm  bor_right" style='width:100%'>
                                    <div class='pad8'>{{item.pay_price}}</div>
                                </div>
                            </div>
                            <div class ="flex_1 flex height40">
                                <div class="flexbox bor_btm  bor_right" style='width:100%'>
                                    <div class='pad8'>{{item.bili}}</div>
                                </div>
                            </div>
                            <div class ="flex_1 flex height40">
                                <div class="flexbox bor_btm  bor_right" style='width:100%'>
                                    <div class='pad8'>{{item.jiesuan}}</div>
                                </div>
                            </div>
                            <div class ="flex_1 flex height40">
                                <div class="flexbox bor_btm  " style='width:100%'>
                                    <div class='pad8'>{{item.remark}}</div>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                </div>
                <!-- 盖章 -->
                <div class='flex'>
                    <div class='flex_1 bor_right'>
                        <div style='margin:20px 20px 40px;text-align:start'>{{qsgs == '威斯腾'?'付款公司：天一集团威斯腾物流（盖章）':'付款公司：天一集团威斯腾物流（盖章）'}}</div>
                        <div style='margin:20px;text-align:start'>经办人：</div>
                        <div style='margin:20px;text-align:start'>部门负责人：</div>
                        <div style='margin:20px;text-align:start'>公司领导人：</div>
                        <div style='margin:20px;text-align:start'>日期：</div>
                    </div>
                    <div class='flex_1 '>
                        <div style='margin:20px 20px 40px;text-align:start'>{{qsgs == '威斯腾'?'收款公司：天一集团威斯腾物流（盖章）':'收款公司：天一集团威斯腾物流（盖章）'}}</div>
                        <div style='margin:20px;text-align:start'>经办人：</div>
                        <div style='margin:20px;text-align:start'>部门负责人：</div>
                        <div style='margin:20px;text-align:start'>公司领导人：</div>
                        <div style='margin:20px;text-align:start'>日期：</div>
                    </div>
                </div>
            </div>
            
        </div>
        <div style='padding-bottom:2%'></div>
        <!-- 加载中... -->
        <div v-if="loading" style="position: fixed;width:100vw;height:100vh;background:rgba(0,0,0,.6);z-index:10;display:flex;top:0;left:0;justify-content: center;align-items: center;">
            <a-spin dot :size="10" />
        </div>
    </div>
  </template>
  <script setup>
  import { ref, reactive,onMounted } from 'vue'
  import { request } from "@/utils/request.js";
  import financialMoneyFzsr from '@/api/financial/financialMoneyFzsr'
  import preview from './preview.vue'
  import { Message } from '@arco-design/web-vue'
  import tool from '@/utils/tool'
  import * as common from '@/utils/common'
  import { ElMapExportTable } from "table-excel";
  import timeFormat from "@/utils/timeFormat.js";
  const showJiesuan = ref(false)
  const showPreview = ref(false)
const fzzt = ref('0')
const qsgs = ref('威斯腾')
const rowData = ref({
    qsgs:'',
    skf:'',
    jsbl:'',
    beizhu:'',
})
const caet_time = ref([])
const loading = ref(false)
const qsgsArr = ref([
    {value:'威斯腾',label:'威斯腾'},
])

const newmons = ref('')
const displayData = ref([])
const displayzongData = ref([])

// 当前时间
const newDate = new Date();
let displayYear = newDate.getFullYear()
let displayMonth = (newDate.getMonth() + 1)>9?(newDate.getMonth() + 1):'0' + (newDate.getMonth() + 1)
// 当年
const newYear = newDate.getFullYear();
// 当月
const newMonth = (newDate.getMonth() + 1)>9?(newDate.getMonth() + 1):'0' + (newDate.getMonth() + 1);

// 本月天数
const newMaxDay = new Date(newYear, newMonth, 0).getDate();
onMounted(() => {
    let fz_date = '';
    fz_date = [`${newYear}-${newMonth}`,`${newYear}-${newMonth}`]
    caet_time.value = [`${newYear}-${newMonth}`,`${newYear}-${newMonth}`]
    handleExportData(fz_date)
});
const handleChangeqsgs = ()=>{
    handleExportData(caet_time.value)
}
const handlePreviewCel = ()=>{
  showPreview.value = false
}
const handleRadioChange = (e)=>{
  crudRef.value.refresh()
}
const handleShowJiesuan = ()=>{
    showJiesuan.value = true
}

// 结算表格合并方法
const testFormData = (item,zongItem,rowIndex,columnIndex) =>{
    let oneArr = []
    let yu1 = []
    let oneNum = 0
    let arr2 = []
    let yu2 = []
    let num2 = 0
    let arr3 = []
    let num3 = 0
    let yu3 = []
    item.map((v,i)=>{
        oneArr.push(oneNum + v.num1)
        yu1.push(v.num1)
        oneNum += v.num1
        if(v.contrat_list.length != 0){
            v.contrat_list.map((vv,ii)=>{
                arr2.push(num2 + vv.num2)
                yu2.push(vv.num2)
                num2 += vv.num2
                vv.goods_type_list.map((vvv,iii)=>{
                    arr3.push(num3 + vvv.num3)
                    yu3.push(vvv.num3)
                    num3 += vvv.num3
                })
            })
        }
    })
    for(let i=0;i<oneArr.length;i++){   // 第一层合并
      if(i == 0){
        if (rowIndex  === 0 && columnIndex === 0) {
            return {
                rowspan: yu1[i],
                colspan: 1,
            };
        }
      }else{
          if (rowIndex  === oneArr[i - 1] && columnIndex === 0) {
              return {
                  rowspan: yu1[i],
                  colspan: 1,
              };
          }
      }
    }
    for(let i=0;i<arr2.length;i++){   // 第二层合并
      if(i == 0){
        if (rowIndex  === 0 && columnIndex === 1) {
            return {
                rowspan: yu2[i],
                colspan: 1,
            };
        }
      }else{
          if (rowIndex  === arr2[i - 1] && columnIndex === 1) {
              return {
                  rowspan: yu2[i],
                  colspan: 1,
              };
          }
      }
    }
    for(let i=0;i<arr3.length;i++){   // 第三层合并
      if(i == 0){
        if (rowIndex  === 0 && columnIndex === 2) {
            return {
                rowspan: yu3[i],
                colspan: 1,
            };
        }
      }else{
          if (rowIndex  === arr3[i - 1] && columnIndex === 2) {
              return {
                  rowspan: yu3[i],
                  colspan: 1,
              };
          }
      }
    }
    for(let i=0;i<arr3.length;i++){   // 总计
        if (rowIndex  === oneArr[oneArr.length - 1] && columnIndex === 0) {
            return {
                rowspan: zongItem.length,
                colspan: 3,
            };
        }
    }
    // 签署公司数据
    if (rowIndex  === oneArr[oneArr.length - 1] + zongItem.length && columnIndex === 0) {
        return {
            rowspan: 1,
            colspan: 4,
        };
    }
    if (rowIndex  === oneArr[oneArr.length - 1] + zongItem.length && columnIndex === 4) {
        return {
            rowspan: 1,
            colspan: 4,
        };
    }
    if (rowIndex  === oneArr[oneArr.length - 1] + zongItem.length + 1 && columnIndex === 0) {
        return {
            rowspan: 1,
            colspan: 4,
        };
    }
    if (rowIndex  === oneArr[oneArr.length - 1] + zongItem.length + 1 && columnIndex === 4) {
        return {
            rowspan: 1,
            colspan: 4,
        };
    }
    if (rowIndex  === oneArr[oneArr.length - 1] + zongItem.length + 2 && columnIndex === 0) {
        return {
            rowspan: 1,
            colspan: 4,
        };
    }
    if (rowIndex  === oneArr[oneArr.length - 1] + zongItem.length + 2 && columnIndex === 4) {
        return {
            rowspan: 1,
            colspan: 4,
        };
    }
    if (rowIndex  === oneArr[oneArr.length - 1] + zongItem.length + 3 && columnIndex === 0) {
        return {
            rowspan: 1,
            colspan: 4,
        };
    }
    if (rowIndex  === oneArr[oneArr.length - 1] + zongItem.length + 3 && columnIndex === 4) {
        return {
            rowspan: 1,
            colspan: 4,
        };
    }
    if (rowIndex  === oneArr[oneArr.length - 1] + zongItem.length + 4 && columnIndex === 0) {
        return {
            rowspan: 1,
            colspan: 4,
        };
    }
    if (rowIndex  === oneArr[oneArr.length - 1] + zongItem.length + 4 && columnIndex === 4) {
        return {
            rowspan: 1,
            colspan: 4,
        };
    }
}
const itemData = ref([])


// 结算导出
const handleExports = ()=> {
      let _data = data
      const instance = new ElMapExportTable(
        {
            column,
            data,
            spanMethod: ({ rowIndex, columnIndex }) => {
                // rowIndex 纵   columnIndex   横  rowspan 纵向合并  colspan横向合并
                return testFormData(itemData.value,displayzongData.value,rowIndex,columnIndex)
            },
            
            setRowStyle({ columnIndex, rowIndex, type }) {
                return {
                    height: 40,
                    alignment: {
                        horizontal: 'left', // 设置文本左对齐
                    },
                };
            },
        },
      );
      instance.download("基础物流汇总结算表" + displayYear + '年' + displayMonth + '月');
}
// 结算表头
let column = [
  {title:`基础物流汇总结算表 ${displayYear} 年 ${displayMonth} 月`,children:[
    {title:'客户名称',dataIndex:'name'},
    {title:'合同号',dataIndex:'contract_str'},
    {title:'业务项目',children:[
        {title:'品名分类',dataIndex:'spName'},
        {title:'计费服务类型',dataIndex:'pay_name'},
      ]
    },
    {title:'总价（元）',dataIndex:'pay_price'},
    {title:'结算比例',dataIndex:'bili'},
    {title:`${qsgs.value=='威斯腾'?'天一集团威斯腾物流':'天一集团威斯腾物流'}`,dataIndex:'jiesuan'},
    {title:'备注',dataIndex:'remark'},
  ]}
]
// 结算数据
let data = []

const handleExport = (e)=>{ // 选择月份
  let range_date = '';
  let arr = e.split('-')
  displayYear= arr[0]
  displayMonth= arr[1]
  column[0].title = `基础物流汇总结算表${displayYear}年${displayMonth}月`
  let maxDay = new Date(arr[0], arr[1], 0).getDate()
  range_date = [e,e]
  caet_time.value = [e,e]
  handleExportData(range_date)
}
const handleExportData = (range_date) =>{
    loading.value = true
  request({
      url:'prediction/Tz/jiesuan',
      method: 'get',
      params:{
            fz_date:range_date,
            qsgs:qsgs.value
      },
  }).then(res=>{
    // 计算预览数据结构
    let _data = res.data.data
    let zongData = res.data.total_price
    let arrzong = []
    _data.map((v,i)=>{
        if(v.contrat_list.length != 0){
            let arrcontrat = []
            let contratArr = []
            v.contrat_list.map((vv,ii)=>{
                if(vv.goods_type_list.length != 0){
                    let arr = []
                    vv.goods_type_list.map((vvv,iii)=>{
                        if(vvv.price_list.length != 0){
                            let arrPrice = []
                            vvv.price_list.map((vvvv,iiii)=>{
                                if(vvvv.pay_price - 0 != 0){
                                    arrPrice.push(vvvv)
                                }
                            })
                            vvv.price_list = arrPrice
                            arr.push(vvv)
                        }
                    })
                    vv.goods_type_list = arr
                    if(vv.goods_type_list.length != 0){
                        contratArr.push(vv)
                        vv.goods_type_list.push({name:'小计',price_list:[{pay_name:'',pay_price:vv.total_price}]})
                        let jiesuan = 0
                        vv.goods_type_list.map((vvv,iii)=>{
                            vvv.price_list.map((vvvv,iiii)=>{
                                if(vvv.name == '小计'){
                                    vvvv.jiesuan = jiesuan.toFixed(2)
                                    vvvv.bili = ''
                                }else{
                                    vvvv.jiesuan = ((vvvv.pay_price - 0) * ((vvvv.bili - 0) / 100)).toFixed(2)
                                    vvvv.bili = ((vvvv.bili - 0) / 100).toFixed(2)
                                    jiesuan += (vvvv.jiesuan - 0)
                                }
                                vvvv.remark = ''
                            })
                        })
                    }else{
                        vv.goods_type_list = []
                        // vv.goods_type_list.push({name:'',price_list:[{pay_name:'',pay_price:'',bili:'',jiesuan:'',remark:''}]})
                    }
                    
                }
            })
            v.contrat_list = contratArr

        }
    })
    displayData.value = _data
    let zongji = 0
    let zongjiesuan = 0
    zongData.map((v,i)=>{
        v.jiesuan = ((v.pay_price - 0) * ((v.bili - 0) / 100)).toFixed(2)
        v.remark = ''
        v.bili = ((v.bili - 0) / 100).toFixed(2)
        zongjiesuan += (v.jiesuan - 0)
        zongji += ((v.pay_price - 0))
    })
    zongjiesuan = zongjiesuan.toFixed(2)
    zongji = zongji.toFixed(2)
    zongData.push({pay_name:'小计',pay_price:zongji,bili:'',jiesuan:zongjiesuan,remark:''})
    displayzongData.value = zongData

    // 配置导出数据
    _data.map((v,i)=>{
        v.num1 = 0
        if(v.contrat_list.length != 0){
            v.contrat_list.map((vv,ii)=>{
                vv.num2 = 0
                vv.goods_type_list.map((vvv,iii)=>{
                    v.num1 += vvv.price_list.length
                    vv.num2 += vvv.price_list.length
                    vvv.num3 = vvv.price_list.length
                })
            })
        }
    })
    let arr = []
    _data.map((v,i)=>{
        if(v.contrat_list.length != 0){
            v.contrat_list.map((vv,ii)=>{
                vv.goods_type_list.map((vvv,iii)=>{
                    vvv.price_list.map((vvvv,iiii)=>{
                        arr.push({...vvvv,spName:vvv.name,contract_str:vv.contract_no,name:v.name,})
                    })
                })
            })
        }else{
            arr.push({bili:'',jiesuan:'',pay_name:'',pay_price:'',remark:'',spName:'',contract_str:'',name:'',})
        }
    })
    zongData.map((v,i)=>{
        arr.push({bili:v.bili,jiesuan:v.jiesuan,pay_name:v.pay_name,pay_price:v.pay_price,remark:v.remark,spName:'',contract_str:'',name:'总计',})
    })
    // 公司签字
    arr.push({
             name:`${qsgs.value=='威斯腾'?'付款公司：天一集团威斯腾物流（盖章）                                .':'付款公司：天一集团威斯腾物流（盖章）                      .'}`,
        contract_str:'',
        spName:'',
        pay_name:'',
        pay_price:`${qsgs.value=='威斯腾'?'收款公司：天一集团威斯腾物流（盖章）                      .':'收款公司：天一集团威斯腾物流（盖章）                                .'}`,
        jiesuan:'',
        bili:'',
        remark:'',
    })
    arr.push({
             name:'经办人：                                                                 .',
        contract_str:'',
        spName:'',
        pay_name:'',
        pay_price:'经办人：                                                                   .',
        jiesuan:'',
        bili:'',
        remark:'',
    })
    arr.push({
             name:'部门负责人：                                                             .',
        contract_str:'',
        spName:'',
        pay_name:'',
        pay_price:'部门负责人：                                                               .',
        jiesuan:'',
        bili:'',
        remark:'',
    })
    arr.push({
             name:'公司领导人：                                                             .',
        contract_str:'',
        spName:'',
        pay_name:'',
        pay_price:'公司领导人：                                                               .',
        jiesuan:'',
        bili:'',
        remark:'',
    })
    arr.push({
             name:'日期：                                                                  .',
        contract_str:'',
        spName:'',
        pay_name:'',
        pay_price:'日期：                                                                    .',
        jiesuan:'',
        bili:'',
        remark:'',
    })


   
      
      data = arr
      itemData.value = _data
    setTimeout(() => {
        loading.value = false
    }, 1000) 
    //   导出表格
    //   handleExports()
  }).catch(rej=>{
    setTimeout(() => {
        loading.value = false
    }, 1000) 
  })
}

const onChange = (e) => {   // 自定义选择时间
        let range_date = '';
        displayYear= e[0].split('-')[0]
        displayMonth= e[0].split('-')[1]
        column[0].title = `基础物流汇总结算表${e[0]}月-${e[1]}月`
        range_date = e
        caet_time.value = e
		// currentTime.value = e
        handleExportData(range_date)
        // console.log('当前选择的日期',currentTime.value)
	};






 
  
  
  
  
 
  </script>
  <style scoped lang="less">
  .home-page-title {
      align-items: center !important;

      img {
          height: 30px;
      }

      .datetime {
          align-items: center;

          p {
              font-size: 20px;
              color: #415b73;
              margin-left: 20px;
              font-style: italic;
          }

          span {
              width: 64px;
              border-radius: 32px;
              padding: 4px 0;
              display: flex;
              justify-content: center;
              align-items: center;
              margin-right: 20px;
              color: #00a0e9;
              border: 1px solid #00a0e9;
              font-size: 14px;
              font-weight: 400;
              cursor: pointer;

              &.active {
                  background: #00a0e9;
                  color: #fff;
              }
          }
      }
  }
</style>
<style>
.tableBox{
    width:100%;
    border:1px solid rgba(0,0,0,.4);
}
.tableBox div{
    box-sizing:border-box;
    text-align:center;
}
.scrollbar{
    scrollbar-width: none;

}
.scrollbar::-webkit-scrollbar {
  display: none; /* 对于Chrome, Safari和Opera */
}
.flexbox{
    display:flex;
    justify-content:center;
    align-items:center;
}
.height40{
    min-height:40px;
}
.bor_btm{
    border-bottom:1px solid rgba(0,0,0,.4);
}
.bor_right{
    border-right:1px solid rgba(0,0,0,.4);
}
.flex_1{
    flex:1;
}
.pad8{
    padding:4px
}
.flex_column{
  flex-direction: column;
}
.calc1{
    width:calc(100% / 8);
}
.calc2{
    width:calc((100% / 8) * 2);
}
.calc3{
    width:calc((100% / 8) * 3);
}
.calc4{
    width:calc((100% / 8) * 4);
}
.calc5{
    width:calc((100% / 8) * 5);
}
.calc6{
    width:calc((100% / 8) * 6);
}
.calc7{
    width:calc((100% / 8) * 7);
}

</style>
  <script> export default { name: 'financial:moneySrfz' } </script>